/*
 * Tezad - Classic puzzle game
 * Copyright 2009 Shayne Riley and Paul Maseberg
 *
 * Tezad is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tezad is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tezad.  If not, see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * To contact the authors on questions or issues regarding the license,
 * you may send an email to <pezads at gmail dot com>
 */

#include "GameMinoEngine.h"

bool GameMinoEngine::isMinoPlacementLegal(const GameWell& well,
        const GameMinoState& minoState, const GameMinoStruct& mino)
{
    int minoRows[4];
    int minoCols[4];
    mino.bricks(minoState, minoRows, minoCols);

    for (int i = 0; i < 4; ++i)
    {
        // If the position of the brick is out of the well, or if the well
        // contains a brick at the same location, it is not legal.
        if (minoRows[i] < 0 || minoRows[i] >= well.height() ||
                minoCols[i] < 0 || minoCols[i] >= well.width() ||
                well.brick(minoRows[i], minoCols[i]) != 0)
        {
            return false;
        }
    }

    return true;
}

GameMinoState GameMinoEngine::settingMinoState(const GameWell& well,
        const GameMinoState& minoState, const GameMinoStruct& mino)
{
    GameMinoState legalState = minoState;

    GameMinoState newState = legalState;
    while (isMinoPlacementLegal(well, newState, mino))
    {
        legalState = newState;
        newState = newState.shiftDown();
    }

    return legalState;
}

void GameMinoEngine::setMino(GameWell& well, const GameMinoState& minoState,
        const GameMinoStruct& mino)
{
    int minoRows[4];
    int minoCols[4];
    mino.bricks(minoState, minoRows, minoCols);

    for (int i = 0; i < 4; ++i)
    {
        // If the position of the brick is inside the well then set it.
        if (minoRows[i] >= 0 && minoRows[i] < well.height() &&
                minoCols[i] >= 0 && minoCols[i] < well.width())
        {
            well.setBrick(minoRows[i], minoCols[i], mino.brickStyle());
        }
    }
}
